import Vue from 'vue'
import VueRouter from 'vue-router'
import asyncRoute from './asyncRoute'
import nprogress from 'nprogress'
import { getCookie, getStore } from '@xingyuelongchen/vue3-storage'
import store from '@/store'
Vue.use(VueRouter)

// 不需要权限的公共路由表
const constantRoutes = [
  { path: '/', name: 'app', meta: { isAuth: true, }, component: () => import('@/layout') },
  { path: '/install', name: 'login', component: () => import('@/views/install') },
  { path: '/login', name: 'login', component: () => import('@/views/login') },
  { path: '/404', name: 'error', component: () => import('@/views/error') },
  { path: '*', name: 'toError', redirect: '/404' }
]

const createRouter = function (routes) {
  return new VueRouter({
    mode: 'hash',
    base: process.env.BASE_URL,
    routes
  });
}
// 重置路由  新版路由，不需要这个方法，因为动态添加的路由与已存在的路由，name相同就会覆盖。
// eslint-disable-next-line no-unused-vars
export const resetRouter = function () {
  const newRouter = createRouter();
  router.matcher = newRouter.matcher
}

// 创建路由
const router = createRouter(constantRoutes);

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
/**
 * 筛选路由 
 * @param {Array} menuTree 菜单树
 * @param {Array} asyncRoutes 路由表
 * @returns 返回匹配过后的路由
 */
const getRoutes = function (menuTree, asyncRoutes) {
  let arr = [];
  menuTree.forEach(e => {
    let item = asyncRoutes.find(b => b.name === e.code);
    if (item) {
      let obj = {
        ...item,
        path: e.path,
        name: e.code,
        meta: Object.assign({}, item.meta, { title: e.name }),
      };
      if (e?.children?.length) obj.children = getRoutes(e.children || [], asyncRoutes);
      arr.push(obj)
    }
  });
  return arr || []
}
/**
 * 挂载路由
 * @param {array} menuTree 菜单树
 */
export const addRouter = async (menuTree = null) => {
  let roles = menuTree || getStore('menuTree') || [];
  // 获取筛选后的路由  
  let routers = getRoutes(roles, asyncRoute());
  if (routers.length) {
    store.commit('setMenu', routers);
    let redirect = '/' + routers[0].path;
    // 挂载路由
    routers.forEach(item => router.addRoute('app', item));
    router.addRoute('app', { path: '*', name: 'error', component: () => import('@/views/error') });
    return { path: redirect }
  }
}
addRouter();
router.beforeEach((to, from, next) => {
  nprogress.start();
  let token = getCookie('token');
  if (to.matched.some(e => e.meta.isAuth) && !token) next('/login');
  else next();
});
router.afterEach(() => {
  nprogress.done()
})
router.onError((err) => {
  console.log('路由错误：', err);
})
export default router
